from .base import PermissionHandler
from stark.service.v1 import StarkConfig, StarkModelForm
from stark.service.v1 import get_choice_text, get_datetime_text
from ..models import House


class ContractConfig(PermissionHandler, StarkConfig):
    
    def get_model_form_class(self, is_add, request, pk, *args, **kwargs):
        class DynamicModelForm(StarkModelForm):
            class Meta:
                model = self.model_class
                fields = "__all__"
            
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                # 获取当前用户的角色
                user = request.tracer.user.roles.first()
                
                if not user:
                    raise ValueError("表单初始化必须传入user参数")
                
                # 1. 基础筛选：根据角色限制房源范围
                # 管理员可以看到所有房源
                print(user.id)
                if user.title == "管理员":
                    base_houses = House.objects.all()
                # 房东只能看到自己名下的房源
                elif user.title == "房东":
                    base_houses = House.objects.filter(landlord_id__house=user.id)
                # 其他角色无权限
                
                else:
                    base_houses = House.objects.none()
                
                # 2. 操作类型筛选：根据添加/编辑状态进一步过滤
                if is_add:
                    # 添加时：只显示空房（在基础筛选范围内）
                    available_houses = base_houses.filter(status="空房")
                    if available_houses.exists():
                        self.fields['house'].queryset = available_houses
                    else:
                        self.fields['house'].choices = [("", "无可用空房")]
                        self.fields['house'].disabled = True
                else:
                    # 编辑时：只显示已租房源（在基础筛选范围内）
                    # 同时确保能看到当前编辑记录关联的房源（即使状态有变化）
                    current_house_id = self.instance.house_id if self.instance else None
                    edited_houses = base_houses.exclude(status="空房")
                    
                    # 如果当前编辑的房源不在筛选结果中，单独加入（避免编辑时找不到原房源）
                    if current_house_id and not edited_houses.filter(id=current_house_id).exists():
                        current_house = House.objects.filter(id=current_house_id).first()
                        if current_house:
                            edited_houses |= House.objects.filter(id=current_house_id)
                    
                    self.fields['house'].queryset = edited_houses
        
        return DynamicModelForm
            
    
    list_display = ["id", "house", "tenant_id", "landlord_id", get_datetime_text("起租日", "start_date"), get_datetime_text("到期日", "end_date"), "total_rent", "water_price", "electricity_price", "gas_price", get_choice_text("合同状态", "status")]

    